package com.wclass.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.wclass.common.*;
import com.wclass.common.alibaba.SmsUtil;
import com.wclass.common.weixinUtil.WechatUtils;
import com.wclass.entity.BaseAppUser;
import com.wclass.entity.BaseCaptcha;
import com.wclass.entity.BaseId;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.service.IBaseAppUserService;
import com.wclass.service.IBaseCaptchaService;
import com.wclass.service.IBaseIdService;
import io.rong.RongCloud;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限控制层
 *
 * @author sensen
 **/
@RestController
@RequestMapping("/index/auth")
@Api(description = "登录注册")
public class AuthApi {
    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private IBaseCaptchaService iBaseCaptchaService;
    @Autowired
    private IBaseIdService iBaseIdService;


    @Value("${alibaba.accessKeyId}")
    private String accessKeyId;
    @Value("${alibaba.accessKeySecret}")
    private String accessKeySecret;
    @Value("${alibaba.signName}")
    private String signName;
    @Value("${rong.appKey}")
    private String appKey;
    @Value("${rong.appSecret}")
    private String appSecret;

    @ApiOperation("绑定手机号")
    @RequestMapping(value = "/bindMobile", method = RequestMethod.POST)
    public ReturnObject bindMobile(@ApiParam("手机号") @RequestParam String phone,
                                   @ApiParam("验证码") @RequestParam String captcha) {
        BaseAppUser record = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone", phone));
        if (record != null) {
            return new ReturnObject(1, "手机号已存在");
        }

        int captchaCount = iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone).eq("captcha", captcha));
        if (captchaCount == 0) {
            return new ReturnObject(1, "请输入正确的验证码");
        }
        if (iBaseCaptchaService.selectCount(
                new EntityWrapper<BaseCaptcha>().eq("phone", phone).eq("captcha", captcha).gt("effective_time", new Date())) == 0) {
            return new ReturnObject(1, "验证码已失效，请重新获取");
        }

        BaseAppUser appUser = new BaseAppUser();
        appUser.setId(BaseContextHandler.getUserID());
        appUser.setPhone(phone);
        iBaseAppUserService.updateById(appUser);
        return new ReturnObject(0, "绑定成功");
    }

    @ApiOperation("判断手机号码是否注册")
    @IgnoreAuth
    @RequestMapping(value = "/judgeMobile", method = RequestMethod.POST)
    public ReturnObject judgeMobile(@ApiParam("用户名【必传】") @RequestParam String username) {

        try {
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone",
                    username));
            if (userVo == null) {
                return new ReturnObject(1, "暂未注册，请先注册");
            }
            return new ReturnObject(0, "可登陆");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @ApiOperation("注册")
    @IgnoreAuth
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ReturnObject register(@ApiParam("用户名【必传】") @RequestParam String username,
                                 @ApiParam("密码【必传】") @RequestParam String password,
                                 @ApiParam("角色类型(0:学生，1：老师)【必传】") @RequestParam Integer type,
                                 @ApiParam("安卓设备唯一") String cid,
                                 @ApiParam("苹果设备唯一") String deviceToken,
                                 @ApiParam("设备类型 android/ios/web") String mobileType) {

        try {
            if (!ToolUtil.checkMobileNumber(username)) {
                return new ReturnObject(1, "用户名（手机号）格式不正确，请重新输入");
            }
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone",
                    username));
            if (userVo != null) {
                return new ReturnObject(1, "用户名（手机号）已存在，请直接登录");
            }
            BaseId baseId = iBaseIdService.getNoUseId(1);

            userVo = new BaseAppUser();
            userVo.setId(Long.parseLong(baseId.getId() + ""));
            userVo.setType(type);
            userVo.setUsername(ToolUtil.GenerateChineseWord());
            userVo.setNickName(ToolUtil.GenerateChineseWord());
            userVo.setPhone(username);
            userVo.setFanNum(0);
            userVo.setFocusNum(0);
            userVo.setAmount(0L);
            userVo.setLevel(1);
            userVo.setAuditStatus(3);
            userVo.setWithdrawAmount(0L);
            userVo.setThawingAmount(0L);
            userVo.setCourseNum(0);
            userVo.setStudentNum(0);
            userVo.setCId(cid);
            userVo.setDeviceToken(deviceToken);
            userVo.setMobileType(mobileType);
            userVo.setRankingNum(iBaseAppUserService.selectCount(new EntityWrapper<>()));
            userVo.setPassword(MD5Utils.encode2hex(password));
            iBaseAppUserService.insert(userVo);

            baseId.setUserState(1);
            iBaseIdService.updateById(baseId);

            UserModel user = new UserModel()
                    .setId(userVo.getId().toString())
                    .setName(username)
                    .setPortrait("http://www.rongcloud.cn/images/logo.png");
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TokenResult result = rongCloud.user.register(user);
            String token = result.getToken();
            userVo.setToken(token);
            iBaseAppUserService.updateById(userVo);
            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());
            return new ReturnObject(0, "注册成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }


    @IgnoreAuth
    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getCaptcha", method = RequestMethod.POST)
    public ReturnObject getCaptcha(@ApiParam("手机号") @RequestParam String phone) throws ClientException {
        //删除历史验证码
        iBaseCaptchaService.delete(new EntityWrapper<BaseCaptcha>().eq("phone", phone));
        //新建验证码
        BaseCaptcha baseCaptcha = new BaseCaptcha(phone, Integer.toString((int) ((Math
                .random() * 9 + 1) * 1000)), DateUtil.getSomeMinute(new Date(), 10));
        iBaseCaptchaService.insert(baseCaptcha);
        Map<String, String> map = Maps.newHashMap();
        map.put("code", baseCaptcha.getCaptcha());
//        map.put("time", "10分钟");
        return SmsUtil.sendSms(phone, "SMS_153410061", map, accessKeyId, accessKeySecret, signName);
    }


    @IgnoreAuth
    @ApiOperation("校验验证码")
    @RequestMapping(value = "/verifyCaptcha", method = RequestMethod.POST)
    public ReturnObject verifyCaptcha(@ApiParam("手机号") @RequestParam String phone,
                                      @ApiParam("验证码") @RequestParam String captcha) {
        //删除历史验证码
        if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone).eq("captcha", captcha)) > 0) {
            if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone)
                    .eq("captcha", captcha).gt("effective_time", new Date())) > 0) {
                return new ReturnObject(0, "验证成功");
            }
            return new ReturnObject(1, "验证码已失效，请重新获取");
        }

        return new ReturnObject(1, "请输入正确的验证码");
    }

    @ApiOperation("更换用户手机号")
    @RequestMapping(value = "/changeUserMobile", method = RequestMethod.POST)
    public ReturnObject changeUserMobile(@ApiParam("旧手机号") @RequestParam String oldPhone,
                                         @ApiParam("新手机号") @RequestParam String newPhone,
                                         @ApiParam("验证码") @RequestParam String captcha){
        BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone", oldPhone));

        if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", newPhone).eq("captcha", captcha)) == 0) {
            return new ReturnObject(1, "请输入正确的验证码");
        }
        if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", newPhone)
                .eq("captcha", captcha).gt("effective_time", new Date())) == 0) {
            return new ReturnObject(1, "验证码已失效，请重新获取");
        }
        int count = iBaseAppUserService.selectCount(new EntityWrapper<BaseAppUser>().eq("phone", newPhone));
        if (count > 0) {
            return new ReturnObject(1, "新手机号已注册");
        }
        userVo.setPhone(newPhone);
        iBaseAppUserService.updateById(userVo);

        return new ReturnObject(0, "用户手机号码更换成功");
    }


    @ApiOperation("登录（手机号码+密码）")
    @IgnoreAuth
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ReturnObject<Object> verify(@ApiParam("用户名【必传】") @RequestParam String username,
                                       @ApiParam("密码【必传】") @RequestParam String password,
                                       @ApiParam("安卓设备唯一") String cid,
                                       @ApiParam("苹果设备唯一") String deviceToken,
                                       @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone",
                    username));
            if (MD5Utils.validate(password, userVo.getPassword())) {
                Map<String,Object> map = Maps.newHashMap();
                map.put("Token",userVo.getToken());
                map.put("userId",userVo.getId());

                iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

                return new ReturnObject<>(0, "登录成功", map);
            }
            return new ReturnObject<>(1, "登录名或密码不正确");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }

    @ApiOperation("忘记密码重新设置")
    @IgnoreAuth
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.POST)
    public ReturnObject<Object> forgetPassword(@ApiParam("手机号") @RequestParam String phone,
                                               @ApiParam("验证码") @RequestParam String captcha,
                                               @ApiParam("新密码") @RequestParam String newpassword) {
        try {

            if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone).eq("captcha",
                    captcha)) > 0) {
                if (iBaseCaptchaService.selectCount(new EntityWrapper<BaseCaptcha>().eq("phone", phone).eq("captcha",
                        captcha).gt("effective_time", new Date())) > 0) {
                    BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone",
                            phone));
                    if (userVo != null) {
                        userVo.setPassword(MD5Utils.encode2hex(newpassword));
                        iBaseAppUserService.updateById(userVo);
                    }

                    return new ReturnObject(0, "验证成功");
                }
                return new ReturnObject(1, "验证码已失效，请重新获取");
            }

            return new ReturnObject<>(1, "验证码不正确");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }


    @ApiOperation("登录（手机号+验证码）")
    @IgnoreAuth
    @RequestMapping(value = "/loginCode", method = RequestMethod.POST)
    public ReturnObject<Object> loginCode(@ApiParam("用户名【必传】") @RequestParam String username,
                                          @ApiParam("安卓设备唯一") String cid,
                                          @ApiParam("苹果设备唯一") String deviceToken,
                                          @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("phone",
                    username));
            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());
            iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

            return new ReturnObject<>(0, "登录成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject<>(12, "系统偷懒了");
        }
    }

    @ApiOperation("修改密码")
    @RequestMapping(value = "/changpassword", method = RequestMethod.POST)
    public ReturnObject changpassword(@ApiParam("新密码") @RequestParam String newpassword) {
        try {
            BaseAppUser userVo = iBaseAppUserService.selectById(BaseContextHandler.getUserID());
            userVo.setPassword(MD5Utils.encode2hex(newpassword));
            iBaseAppUserService.updateById(userVo);

            return new ReturnObject(0, "密码修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }


    /**
     * 微信 web 一键登录
     */
    @IgnoreAuth
    @PostMapping("authweixin")
    @ApiOperation("微信 一键登录(无token验证)")
    public ReturnObject authweixin(@ApiParam("code") @RequestParam String code,
                                   @ApiParam("安卓设备唯一") String cid,
                                   @ApiParam("苹果设备唯一") String deviceToken,
                                   @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            Map<String, String> data = new HashMap();
            Map<String, String> result = WechatUtils.getUserInfoAccessToken(code);//通过这个code获取access_token
            String openId = result.get("openid");
            String accessToken = result.get("access_token");

            //使用access_token获取用户信息
            Map<String, String> userInfo = WechatUtils.getUserInfo(accessToken, openId);

            //用户登录
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("weixin", userInfo.get("unionid")));
            if (userVo != null) {
                Map<String,Object> map = Maps.newHashMap();
                map.put("Token",userVo.getToken());
                map.put("userId",userVo.getId());
                return new ReturnObject(250, "用户名已存在，请直接登录", map);
            }

            String nickname = EmojiFilter.filterEmoji(userInfo.get("nickname"));
            BaseId baseId = iBaseIdService.getNoUseId(1);

            userVo = new BaseAppUser();
            userVo.setId(Long.parseLong(baseId.getId() + ""));
            userVo.setPictureAddress(userInfo.get("headimgurl"));
            userVo.setType(0);
            userVo.setWeixin(userInfo.get("unionid"));
            userVo.setUsername(nickname);
            userVo.setNickName(nickname);
            userVo.setState(0);
            userVo.setCrtTime(new Date());
            userVo.setLoginTime(new Date());
            userVo.setSex(Integer.parseInt(userInfo.get("sex")));
            userVo.setFanNum(0);
            userVo.setFocusNum(0);
            userVo.setAmount(0L);
            userVo.setLevel(1);
            userVo.setAuditStatus(3);
            userVo.setWithdrawAmount(0L);
            userVo.setThawingAmount(0L);
            userVo.setCourseNum(0);
            userVo.setStudentNum(0);
            userVo.setRankingNum(iBaseAppUserService.selectCount(new EntityWrapper<>()));
            iBaseAppUserService.insert(userVo);

            baseId.setUserState(1);
            iBaseIdService.updateById(baseId);

            iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

            //注册融云账号
            UserModel user = new UserModel()
                    .setId(userVo.getId().toString())
                    .setName(nickname)
                    .setPortrait("http://www.rongcloud.cn/images/logo.png");
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TokenResult result_ry = null;
            result_ry = rongCloud.user.register(user);
            String token = result_ry.getToken();
            userVo.setToken(token);
            iBaseAppUserService.updateById(userVo);

            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());

            return new ReturnObject(0, "注册成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    /**
     * 微信 web 一键登录
     */
    @IgnoreAuth
    @PostMapping("authWeixinMobile")
    @ApiOperation("微信 一键登录(无token验证)")
    public ReturnObject authWeixinMobile(@ApiParam("用户信息json") @RequestParam String userInfo,
                                         @ApiParam("安卓设备唯一") String cid,
                                         @ApiParam("苹果设备唯一") String deviceToken,
                                         @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            JSONObject userInfoObj = JSON.parseObject(userInfo);

            //用户登录
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("weixin", userInfoObj.get("unionid")));
            if (userVo != null) {
                return new ReturnObject(250, "用户名已存在，请直接登录", userVo.getToken());
            }

            BaseId baseId = iBaseIdService.getNoUseId(1);

            String nickname = EmojiFilter.filterEmoji(userInfoObj.get("nickname").toString());
            userVo = new BaseAppUser();
            userVo.setId(Long.parseLong(baseId.getId() + ""));
            userVo.setPictureAddress(userInfoObj.get("headimgurl").toString());
            userVo.setType(0);
            userVo.setWeixin(userInfoObj.get("unionid").toString());
            userVo.setUsername(nickname);
            userVo.setNickName(nickname);
            userVo.setState(0);
            userVo.setCrtTime(new Date());
            userVo.setLoginTime(new Date());
            userVo.setSex(Integer.parseInt(userInfoObj.get("sex").toString()));
            userVo.setFanNum(0);
            userVo.setFocusNum(0);
            userVo.setAmount(0L);
            userVo.setLevel(1);
            userVo.setAuditStatus(3);
            userVo.setWithdrawAmount(0L);
            userVo.setThawingAmount(0L);
            userVo.setCourseNum(0);
            userVo.setStudentNum(0);
            userVo.setRankingNum(iBaseAppUserService.selectCount(new EntityWrapper<>()));
            iBaseAppUserService.insert(userVo);

            baseId.setUserState(1);
            iBaseIdService.updateById(baseId);

            iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

            //注册融云账号
            UserModel user = new UserModel()
                    .setId(userVo.getId().toString())
                    .setName(nickname)
                    .setPortrait("http://www.rongcloud.cn/images/logo.png");
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TokenResult result_ry = null;
            result_ry = rongCloud.user.register(user);
            String token = result_ry.getToken();
            userVo.setToken(token);
            iBaseAppUserService.updateById(userVo);

            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());

            return new ReturnObject(0, "注册成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    /**
     * QQ 一键登录
     */
    @IgnoreAuth
    @PostMapping("authqq")
    @ApiOperation("QQ一键登录(无token验证)")
    public ReturnObject authqq(@ApiParam("openId") @RequestParam String openId,
                               @ApiParam("accessToken") @RequestParam String accessToken,
                               @ApiParam("appId") @RequestParam String appId,
                               @ApiParam("安卓设备唯一") String cid,
                               @ApiParam("苹果设备唯一") String deviceToken,
                               @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            String html = HttpRequest.sendGet("https://graph.qq.com/user/get_user_info", "access_token=" + accessToken + "&oauth_consumer_key=" + appId + "&openid=" + openId);
            JSONObject jsonObject = JSONObject.parseObject(html);
            Integer ret = jsonObject.getInteger("ret");
            String msg = jsonObject.getString("msg");

            if (ret != 0) {
                return new ReturnObject(1, "获取用户QQ信息失败");
            }
            /**
             *  用户昵称
             *  可能存在4个字节的utf-8字符，MySQL默认不支持，直接插入会报错，所以过滤掉
             **/
            String nickname = ToolUtil.filterUtf8mb4(jsonObject.getString("nickname")).trim(); // 这个方法可以自行百度
            // figureurl_qq_2=QQ的100*100头像，figureurl_2=QQ 100&100空间头像，QQ头像不一定有，空间头像一定有
            /**
             * 头像
             */
            String avatar = jsonObject.getString("figureurl_qq_2");
            if (avatar != null && !avatar.isEmpty()) {
                avatar = jsonObject.getString("figureurl_2");
            }
            /**
             * 性别
             */
            String gender = jsonObject.getString("gender");

            BaseId baseId = iBaseIdService.getNoUseId(1);

            //用户登录
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("tencent", openId));
            if (userVo != null) {
                Map<String,Object> map = Maps.newHashMap();
                map.put("Token",userVo.getToken());
                map.put("userId",userVo.getId());
                return new ReturnObject(250, "用户名已存在，请直接登录", map);
            }
            userVo = new BaseAppUser();
            userVo.setId(Long.parseLong(baseId.getId() + ""));
            userVo.setType(0);
            userVo.setUsername(nickname);
            userVo.setNickName(nickname);
            userVo.setTencent(openId);
            userVo.setPictureAddress(avatar);
            userVo.setCrtTime(new Date());
            userVo.setLoginTime(new Date());
            userVo.setSex(gender.equals("男") ? 1 : 2);
            userVo.setFanNum(0);
            userVo.setFocusNum(0);
            userVo.setAmount(0L);
            userVo.setLevel(1);
            userVo.setAuditStatus(3);
            userVo.setWithdrawAmount(0L);
            userVo.setThawingAmount(0L);
            userVo.setCourseNum(0);
            userVo.setStudentNum(0);
            userVo.setRankingNum(iBaseAppUserService.selectCount(new EntityWrapper<>()));
            iBaseAppUserService.insert(userVo);

            baseId.setUserState(1);
            iBaseIdService.updateById(baseId);

            iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

            //注册融云账号
            UserModel user = new UserModel()
                    .setId(userVo.getId().toString())
                    .setName(nickname)
                    .setPortrait("http://www.rongcloud.cn/images/logo.png");
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TokenResult result = null;
            result = rongCloud.user.register(user);
            String token = result.getToken();
            userVo.setToken(token);
            iBaseAppUserService.updateById(userVo);

            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());

            return new ReturnObject(0, "注册成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }

    }

    /**
     * QQ 一键登录
     */
    @IgnoreAuth
    @PostMapping("authqqMobile")
    @ApiOperation("QQ一键登录(无token验证)")
    public ReturnObject authqqMobile(@ApiParam("用户信息json") @RequestParam String userInfo,
                                     @ApiParam("安卓设备唯一") String cid,
                                     @ApiParam("苹果设备唯一") String deviceToken,
                                     @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(userInfo);
            Integer ret = jsonObject.getInteger("ret");
            String msg = jsonObject.getString("msg");

            if (ret != 0) {
                return new ReturnObject(1, "获取用户QQ信息失败");
            }
            /**
             *  用户昵称
             *  可能存在4个字节的utf-8字符，MySQL默认不支持，直接插入会报错，所以过滤掉
             **/
            String nickname = ToolUtil.filterUtf8mb4(jsonObject.getString("nickname")).trim(); // 这个方法可以自行百度
            // figureurl_qq_2=QQ的100*100头像，figureurl_2=QQ 100&100空间头像，QQ头像不一定有，空间头像一定有
            /**
             * 头像
             */
            String avatar = jsonObject.getString("figureurl_qq");
            if (avatar != null && !avatar.isEmpty()) {
                avatar = jsonObject.getString("figureurl_2");
            }
            /**
             * 性别
             */
            String gender = jsonObject.getString("gender");

            BaseId baseId = iBaseIdService.getNoUseId(1);

            //用户登录
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("tencent", jsonObject.getString("openId")));
            if (userVo != null) {
                return new ReturnObject(250, "用户名已存在，请直接登录", userVo.getToken());
            }
            userVo = new BaseAppUser();
            userVo.setId(Long.parseLong(baseId.getId() + ""));
            userVo.setType(0);
            userVo.setUsername(nickname);
            userVo.setNickName(nickname);
            userVo.setTencent(jsonObject.getString("openId"));
            userVo.setPictureAddress(avatar);
            userVo.setCrtTime(new Date());
            userVo.setLoginTime(new Date());
            userVo.setSex(gender.equals("男") ? 1 : 2);
            userVo.setFanNum(0);
            userVo.setFocusNum(0);
            userVo.setAmount(0L);
            userVo.setLevel(1);
            userVo.setAuditStatus(3);
            userVo.setWithdrawAmount(0L);
            userVo.setThawingAmount(0L);
            userVo.setCourseNum(0);
            userVo.setStudentNum(0);
            userVo.setRankingNum(iBaseAppUserService.selectCount(new EntityWrapper<>()));
            iBaseAppUserService.insert(userVo);

            baseId.setUserState(1);
            iBaseIdService.updateById(baseId);

            iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

            //注册融云账号
            UserModel user = new UserModel()
                    .setId(userVo.getId().toString())
                    .setName(nickname)
                    .setPortrait("http://www.rongcloud.cn/images/logo.png");
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TokenResult result = null;
            result = rongCloud.user.register(user);
            String token = result.getToken();
            userVo.setToken(token);
            iBaseAppUserService.updateById(userVo);

            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());

            return new ReturnObject(0, "注册成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }

    }


    /**
     * 微博 一键登录

    @PostMapping("authweibo")
    @ApiOperation("微博 一键登录(无token验证)")
    public ReturnObject authweibo(@ApiParam("code") @RequestParam String code,
                                  @ApiParam("返回地址url") @RequestParam String redirectUri,
                                  @ApiParam("安卓设备唯一") String cid,
                                  @ApiParam("苹果设备唯一") String deviceToken,
                                  @ApiParam("设备类型 android/ios/web") String mobileType) {
        try {
            String appId = "2907636341";
            String appSecret = "7c4565a089f520d553dd89fb0dee4b57";
            String authPath = "";
            String parater = "client_id=" + appId
                    + "&client_secret=" + appSecret
                    + "&grant_type=authorization_code"
                    + "&redirect_uri=" + redirectUri
                    + "&code=" + code;

            //  用code换取accessToken
            String result = HttpRequest.sendPost("https://api.weibo.com/oauth2/access_token", parater);
            JSONObject resp = JSONObject.parseObject(result);
            Integer errorCode = resp.getInteger("error_code");
            String error = resp.getString("error");
            String errorMsg = resp.getString("error_description");
            if (errorCode != null && errorCode != 0) {
                return new ReturnObject(1, error + (errorMsg == null ? "" : errorMsg), null);
            }
            String accessToken = (String) resp.get("access_token");
            String uid = (String) resp.get("uid"); // 这个uid就是微博用户的唯一用户ID，可以通过这个id直接访问到用户微博主页
//            int expires = (Integer) resp.get("expires_in"); // 有效期，单位秒
            // 用uid和accessToken换取用户信息
            String result_user = HttpRequest.sendGet("https://api.weibo.com/2/users/show.json", "access_token=" + accessToken + "&uid=" + uid);

            JSONObject resp_user = JSONObject.parseObject(result_user);
            String nickname = (String) resp_user.get("name");
            // 微博180*180高清头像
            String avatar = (String) resp_user.get("profile_image_url");
            //用户登录
            //用户登录
            BaseAppUser userVo = iBaseAppUserService.selectOne(new EntityWrapper<BaseAppUser>().eq("sina", uid));
            if (userVo != null) {
                return new ReturnObject(0, "用户名已存在，请直接登录", userVo.getToken());
            }
            userVo = new BaseAppUser();
            userVo.setType(0);
            userVo.setNickName(nickname);
            userVo.setSina(uid);
            userVo.setFanNum(0);
            userVo.setFocusNum(0);
            userVo.setAmount(0L);
            userVo.setLevel(1);
            userVo.setPictureAddress(avatar);
            userVo.setAuditStatus(3);
            userVo.setWithdrawAmount(0L);
            userVo.setThawingAmount(0L);
            userVo.setCourseNum(0);
            userVo.setStudentNum(0);
            userVo.setRankingNum(iBaseAppUserService.selectCount(new EntityWrapper<>()));
            iBaseAppUserService.insert(userVo);

            iBaseAppUserService.updataDevideInfo(userVo, cid, deviceToken, mobileType);

            //注册融云账号
            UserModel user = new UserModel()
                    .setId(userVo.getId().toString())
                    .setName(nickname)
                    .setPortrait("http://www.rongcloud.cn/images/logo.png");
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            TokenResult result_ry = null;
            result_ry = rongCloud.user.register(user);
            String token = result_ry.getToken();
            userVo.setToken(token);
            iBaseAppUserService.updateById(userVo);

            Map<String,Object> map = Maps.newHashMap();
            map.put("Token",userVo.getToken());
            map.put("userId",userVo.getId());

            return new ReturnObject(0, "注册成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }*/
}
